<?php

declare(strict_types=1);

namespace app\model;

use app\common\facade\auth\Auth;
use app\model\base\BaseCouponExtensionModel;

/**
 *
 *
 * @mixin \think\Model
 * @property int $id
 * @property int $obj_id 用户名
 * @property string $channel_name 渠道名
 * @property int $type 类型
 * @property int $status 状态1正常2停止
 * @property int $channel_id 渠道id
 * @property int $agent_id 代理id
 * @property-read \app\model\CouponBrand $coupon_brand
 * @property-read \app\model\CouponProductChannel $coupon_product_channel
 */
class CouponExtension extends BaseCouponExtensionModel
{

    const EXTENSION_TYPE_YES = 'yes';
    const EXTENSION_TYPE_NO = 'no';


    const TYPE_PRODUCT = 1;
    const TYPE_BRAND = 2;
    const TYPE_CPS = 3;
    const TYPE_MEITUAN_COUPON = 4; // 美团券包


    /**
     * 获取产品推广链接
     * @param $id
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function product($id)
    {
        $type = self::TYPE_PRODUCT;

        /**
         * @var CouponProduct $couponProduct
         */
//        $couponProductChannel = CouponProductChannel::query()->where('id', $id)->find();


        $couponProduct = CouponProduct::query()->where('id', $id)->find();


        if (empty($couponProduct->brand_type)) return false;


        $channel_name = $this->getChannelName($couponProduct->id, $type);

        if (!$couponProduct) return false;

        $basePath = env('app.api_url') . '/topup/quanyi/detail?channel=' . $channel_name . '&brandId=' . $couponProduct->brand_type->brand_id . '&product_id=' . $couponProduct->id.'&extension_type='.$type;

        return $basePath;


    }

    /**
     * 获取品牌推广链接
     * @param $id
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function brand($id)
    {
        $type = self::TYPE_BRAND;
        $channel_name = $this->getChannelName($id, $type);
        /**
         * @var CouponProductChannel $couponProductChannel
         */
        $couponBrand = CouponBrand::query()->where('id', $id)->find();

        if (!$couponBrand) return false;

        $basePath = env('app.api_url') . '/topup/quanyi/detail?channel=' . $channel_name . '&brandId=' . $couponBrand->id.'&extension_type='.$type;

        return $basePath;
    }

    /**
     * 获取活动推广链接
     * @param $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cps($id)
    {
        $type = self::TYPE_CPS;

        $channel_name = $this->getChannelName($id, $type);

        $couponBrand = CouponBrand::query()->where('id', $id)->find();

        $basePath = env('app.api_url') . '/topup/transferPage/index?channel=' . $channel_name . '&act_id=' . $couponBrand->act_id.'&extension_type='.$type;
        return $basePath;
    }

    /**
     * agent/coupon.Url/generate
     * 获取美团券包推广链接
     * @param $id
     */
    public function coupon($id) {
        $type = self::TYPE_MEITUAN_COUPON;

        $agentChannel = $this->getChannelInfo($id, $type);
        $meituan = new \app\common\service\Meituan(Auth::agentId());

        // _coupon_user_id 默认美团券包用户标识
        $user = MobileUser::findOrCreate(['openid' => Auth::agentId() . '_coupon_user_id', 'agent_id' => Auth::agentId()], ['app_id' => 'coupon', 'token' => (microtime(true)*10000).rand(1,999999999999)]);

        $meituanRes = $meituan->generateLink([
            'user_id' => $user->id,
            'agent_id' => Auth::agentId(),
            'channel_id' => $agentChannel->id,
            'act_id' => $id,
        ]);

        return $meituanRes;
    }

    /**
     * @return \think\model\relation\HasOne
     */
    public function couponBrand()
    {
        return $this->hasOne(CouponBrand::class, 'id', 'obj_id');
    }

    /**
     * @return \think\model\relation\HasOne
     */
    public function couponProductChannel()
    {
        return $this->hasOne(CouponProductChannel::class, 'product_id', 'obj_id');
    }

    /**
     * 默认渠道信息
     * @param $id
     * @param $type
     */
    private function getChannelInfo($id, $type) {
        /**@var AgentChannel $agentChannel * */
        $agentChannel = $this->getDefaultChannel();
        /**@var self $obj * */
        self::findOrCreate([
            'type' => $type,
            'obj_id' => $id,
            'channel_id' => $agentChannel->id,
            'channel_name' => $agentChannel->getAttr('name'),
            'agent_id' => Auth::agentId(),
        ]);
        return $agentChannel;
    }


    /**
     * 获取默认的渠道名
     */
    private function getChannelName($id, $type)
    {

        $agentChannel = $this->getChannelInfo($id, $type);

        return $agentChannel->getAttr('name');


    }

    /**
     * 获取默认的渠道
     */
    public function getChannelId()
    {


        /**@var AgentChannel $agentChannel * */
        $agentChannel = $this->getDefaultChannel();

        return $agentChannel->id;

    }

    private function getDefaultChannel()
    {

        /**@var AgentChannel $agentChannel * */
        $agentChannel = AgentChannel::findOrNew([
            'channel_type' => AgentChannel::CHANNEL_TYPE_BRAND_EXTENSION,
            'agent_id' => Auth::agentId(),
        ]);

        if (!$agentChannel->id) {
            $agentChannel->setAttr('name', $agentChannel->getRandomChannelName());
            $agentChannel->remark = '默认推广渠道';
            $agentChannel->template_id = 2;
            $agentChannel->is_sys = 1;
            $agentChannel->save();
            //新建的渠道给他足够的权限
            (new AgentChannel())->getCommonChannelTemplateService($agentChannel->id);
        }

        return $agentChannel;

    }


    /**
     * 已推广的链接
     */
    public function getAlready($type = '')
    {

        $couponExtension = CouponExtension::query()
            ->where('agent_id', Auth::agentId())
            ->when($type, function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->column('obj_id');

        return $couponExtension ?? [];
    }


}
